package com.yfp.machine.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.yfp.common.core.constant.EmqxConstants;
import com.yfp.common.core.domain.R;
import com.yfp.emqx.MqttSendClient;
import com.yfp.machine.domain.Machine;
import com.yfp.machine.domain.MachineTemp;
import com.yfp.machine.domain.dto.FrequencyReportDTO;
import com.yfp.machine.mapper.MachineMapper;
import com.yfp.machine.mapper.MachineTempMapper;
import com.yfp.machine.service.MachineTempService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 设备稳定记录
 * 
 * @CreateDate: 2024/9/26 10:33
 * @UpdateUser: 
 * @UpdateDate: 2024/9/26 10:33
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@Service
@Slf4j
public class MachineTempServiceImpl implements MachineTempService {
    @Autowired
    private MachineTempMapper machineTempMapper;
    @Resource
    private MqttSendClient mqttSendClient;
    @Resource
    private MachineMapper machineMapper;




    @Override
    public List<MachineTemp> findByMachineId(String machineId, Date startDate, Date endDate) {
        return machineTempMapper.findByMachineId(machineId, startDate, endDate);
    }

    /**
     * 温度上报频率
     * @param frequencyReportDTO
     */
    @Override
    @Transactional
    public void frequencyReport(FrequencyReportDTO frequencyReportDTO) {
        String recordNo = UUID.randomUUID().toString();
        JSONObject pushObj = new JSONObject();
        // 主题推送消息类型      7
        pushObj.set(EmqxConstants.TOPIC_PUSH_MSG_TYPE, EmqxConstants.FREQUENCY_REPORT);
        // 主题推送时间
        pushObj.set(EmqxConstants.TOPIC_PUSH_TIME, DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        // 主题推送记录编号
        pushObj.set(EmqxConstants.TOPIC_PUSH_RECORD_NO, recordNo);
        // 频次
        pushObj.set(EmqxConstants.TOPIC_PUSH_REPORT_FREQUENCY,frequencyReportDTO.getFrequency());
        try {
            // 主题topic   yfp/machine/ + 设备id
            mqttSendClient.publish(false, frequencyReportDTO.getMachineId(), pushObj.toString());
        } catch (MqttException e) {
            log.info("推送设备重启失败");
        }

        Machine machine = new Machine();
        machine.setMachineId(frequencyReportDTO.getMachineId());
        machine.setTempFrequency(frequencyReportDTO.getFrequency());
        machineMapper.update(machine);
    }

    /**
     * 获取上传频率
     * @param machineId
     * @return
     */
    @Override
    public Integer getFrequency(String machineId) {
        return machineMapper.queryById(machineId).getTempFrequency();
    }
}
